<?php
declare(strict_types=1);
namespace App\Dao;

use App\Model\Lottery;

class LotteryDao {

    /**
     * 获取用户的抽奖次数
     * @param $openid
     * @return int|mixed|null
     */
    public function getPrizeCount($openid)
    {
        return Lottery::query()->where('openid',$openid)->orderBy('id', 'desc')->value('prize_count') ?? 0;
    }


    /**
     * @param [type] $data
     * @return int
     * @Description  新增一条抽奖次数记录
     */
    public function addLottery($data)
    {
        $prize_count = $this->getPrizeCount($data['openid']);
        $map['prize_id'] = $data['prize_id'] ?? 0;
        $map['openid'] = $data['openid'];
        $map['remark'] = $data['remark'];
        $map['remark_desc'] = $data['remark_desc'];
        $map['add_time'] = time();
        $map['prize_count'] = $prize_count + $data['count'];
        $map['count'] = $data['count'];
        $map['type'] = $data['type'];
        $map['order_no'] = empty($data['order_no']) ? '': $data['order_no'];
        return $this->add($map);
    }

    /**
     * 新建
     * @param $insertArray
     * @return int
     */
    public function add($insertArray)
    {
        return Lottery::query()->insertGetId($insertArray);

    }

    /**
     * 查询
     * @param $where
     * @param string[] $columns
     * @return array
     */
    public function findByWhere($where, $columns=['*'])
    {
        return Lottery::query()->where($where)->first($columns);
    }

    /**
     * 获取抽奖列表
     * @param array $where
     * @param string[] $columns
     * @param int $pageSize
     * @param null $page
     * @return array
     */
    public function getListPage($where=[], $columns=['*'], $pageSize=15, $page=null)
    {
        $data = Lottery::query()->leftJoin('coupon_log', 'lottery.id', '=', 'coupon_log.lottery_id')
            ->where($where)->orderBy('lottery.id', 'dosc')
            ->paginate(intval($pageSize),$columns, 'page', $page)
            ->toArray();
        $count = Lottery::query()->leftJoin('coupon_log', 'lottery.id', '=', 'coupon_log.lottery_id')->where($where)->count();
        return [
            'list' => @$data['data'],
            'count' => $count
        ];
    }

    


}